import pymongo
from dependencies.myMongo.mongoDbClient import MongoDbClient


# 查询数据清洗 过滤掉objectId
def to_subs(params):
    if isinstance(params, dict):
        return {key: val for key, val in params.items() if key != '_id'}
    if isinstance(params, pymongo.cursor.Cursor):
        obs = []
        for i in params:
            lis = {key: val for key, val in i.items() if key != '_id'}
            obs.append(lis)
        return obs
    return ''


class MongoUtil(MongoDbClient):

    def __init__(self):
        super(MongoUtil, self).__init__()
        self.db = None
        self.table = None

    def _connection(self, db, table):
        self.connection()
        self.db = self.conn[db]
        self.table = self.db[table]

    # 查询列表
    def find(self, param=None):
        if param is None:
            param = {}
        result = to_subs(self.table.find(param))
        return result

    # 查询单个对象
    def find_one(self, param):
        result = to_subs(self.table.find_one(param))
        return result

    # 插入单条
    def insert_one(self, param):
        return self.table.insert_one(param)

    # 插入多条
    def insert_many(self, param):
        return self.table.insert_many(param)

    # 覆盖单条数据字段
    def update_set_one(self, query, update):
        return self.table.update(query, {'$set': update})

    # 自增单条数据字段
    def update_inc_one(self, query, update):
        return self.table.update(query, {'$inc': update})

    @classmethod
    def _get_connection(cls, db, table):
        client = cls()
        client._connection(db, table)
        return client
